#include "StdAfx.h"
#include "SAPINotifySink.h"
#include "sphelper.h"
#include <iostream>
#include "time.h"

SAPINotifySink::SAPINotifySink(void)
{
	refCount = 0;
	pRecoContext = NULL;
	pVoice = NULL;
}

SAPINotifySink::~SAPINotifySink(void)
{
}

HRESULT SAPINotifySink::QueryInterface(const IID& riid, void** ppvObject)
{
	return S_FALSE;
}
ULONG SAPINotifySink::AddRef()
{
	return ++refCount;
}
ULONG SAPINotifySink::Release()
{
	return --refCount;
}


void SAPINotifySink::Speak(WCHAR* message)
{
	lastMessage.assign(message);
	done = false;
	startTime = clock();
	inputStartedTime = 0;
	pVoice->Speak( message, SPF_ASYNC/*SPF_DEFAULT*/, NULL);
}

static ULONGLONG lastPos = 0;
HRESULT SAPINotifySink::Notify()
{
	HRESULT hr = S_OK;
	/*
	SPEVENT* pEvent = new SPEVENT();
	while(hr==S_OK)
	{
		hr = pVoice->GetEvents(1, pEvent, NULL);
		std::cout << pEvent->eEventId;
	}
	delete pEvent;
	*/
	CSpEvent eventHelper;
	if(pVoice)
	{
		hr = eventHelper.GetFrom(pVoice);
	}
	else if(pRecoContext)
	{
		hr = eventHelper.GetFrom(pRecoContext);
	}


	

	SPPHONEID phoneId;
	std::wstring str;
	if(SUCCEEDED(hr))
	{		
		if(eventHelper.ullAudioStreamOffset>lastPos)
		{
			/*
			//let's read what's been created in the meanwhile
			LARGE_INTEGER li;
			li.HighPart=0;
			li.LowPart=0;
			li.QuadPart=0;
			pStream->Seek(li, STREAM_SEEK_SET, NULL);

			ULONGLONG len = eventHelper.ullAudioStreamOffset-lastPos;//148666;//4096*2*2*2*2;
			ULONG read = 0;
			char* buf = new char[len*2];
			hr = pStream->Read(buf, len*2, &read);
			if(read>0)
			{
				lastPos += read;
				short* sample = (short*)buf;
				for(int i=0; i<read/2; i++)
				{
					samples.push_back(sample[i]);
				}
			}
			*/
		}

		if(eventHelper.elParamType==SPET_LPARAM_IS_STRING)
		{
			const WCHAR* tmp = eventHelper.String();
			str.assign(tmp);
		}
		if(eventHelper.eEventId==SPEI_RECOGNITION)
		{
			ISpRecoResult* pResult = eventHelper.RecoResult();
			
			SPPHRASE* pPhrase;
			hr = pResult->GetPhrase(&pPhrase);

			WCHAR* pText;
			hr = pResult->GetText(SP_GETWHOLEPHRASE, SP_GETWHOLEPHRASE, TRUE, &pText, NULL);
			std::wcout << pText << std::endl;

			::CoTaskMemFree(pText);
		}

		switch(eventHelper.eEventId)
		{
		case SPEI_START_INPUT_STREAM:
			lastPos = 0;
			break;
		case SPEI_PHONEME:
			if(!inputStartedTime)
			{
				inputStartedTime = clock();
			}
			//phoneId = eventHelper.Phoneme();
			break;
		case SPEI_VISEME:
			if(!inputStartedTime)
			{
				inputStartedTime = clock();
			}
			//phoneId = eventHelper.Phoneme();
			break;
		case SPEI_WORD_BOUNDARY:
			if(!inputStartedTime)
			{
				inputStartedTime = clock();
			}
			break;
		case SPEI_END_INPUT_STREAM:
			stopTime = clock();
			done = true;
			break;
		default:
			std::cout << eventHelper.eEventId << std::endl;
			break;
		}
	}
	return S_OK;
}
